from pydantic import BaseModel, Field, validator
from typing import Optional, TypeVar, Generic, List, Dict, Any
from datetime import datetime, date
from enum import Enum
import json

T = TypeVar('T')

class BaseSchema(BaseModel):
    """
    基础 Schema 类，所有 Schema 都应继承此类
    提供通用配置和常用方法
    """
    class Config:
        from_attributes = True
        json_encoders = {
            datetime: lambda v: v.strftime("%Y-%m-%d %H:%M:%S"),
            date: lambda v: v.strftime("%Y-%m-%d"),
        }
        arbitrary_types_allowed = True
        use_enum_values = True

    @classmethod
    def validate_json(cls, json_str: str):
        """验证 JSON 字符串并返回解析后的对象"""
        try:
            data = json.loads(json_str)
            return cls.parse_obj(data)
        except (json.JSONDecodeError, ValueError) as e:
            raise e

    def to_dict(self, exclude_none: bool = True, **kwargs) -> Dict[str, Any]:
        """将 Schema 转换为字典"""
        return self.dict(exclude_none=exclude_none, **kwargs)

    def to_json(self, exclude_none: bool = True, **kwargs) -> str:
        """将 Schema 转换为 JSON 字符串"""
        return self.json(exclude_none=exclude_none, **kwargs)

class PaginatedSchema(BaseSchema, Generic[T]):
    """
    分页响应 Schema
    """
    # total: int = Field(..., description="总记录数")
    # items: List[T] = Field(..., description="当前页数据列表")
    page: int = Field(1, description="当前页码")
    size: int = Field(10, description="每页数量")

    # @validator('items', pre=True)
    # def convert_items(cls, v):
    #     """确保 items 是列表"""
    #     return list(v) if v is not None else []

class StatusEnum(str, Enum):
    """
    通用状态枚举
    """
    ENABLED = "enabled"
    DISABLED = "disabled"
    DELETED = "deleted"

class OrderEnum(str, Enum):
    """
    排序枚举
    """
    ASC = "asc"
    DESC = "desc"